package com.mmall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.mmall.common.IConst;
import com.mmall.common.ResponseInfo;
import com.mmall.common.ServerResponse;
import com.mmall.dao.CategoryMapper;
import com.mmall.dao.ProductMapper;
import com.mmall.pojo.Category;
import com.mmall.pojo.Product;
import com.mmall.service.ICategoryService;
import com.mmall.service.IProductService;
import com.mmall.util.DateTimeUtil;
import com.mmall.util.PropertiesUtil;
import com.mmall.vo.ProductDetailVo;
import com.mmall.vo.ProductListVo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.stereotype.Service;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

/**
 * 商品管理逻辑层实现类
 * Created by qezhhnjy on 2017/9/27-22:48.
 */
@Service("iProductService")
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class ProductServiceImpl implements IProductService {

    @Resource
    private ProductMapper productMapper;

    @Resource
    private CategoryMapper categoryMapper;

    @Resource
    private ICategoryService iCategoryService;

    /**
     * 插入或者更新商品信息
     *
     * @param product 商品对象
     * @return 响应对象
     */
    @Override
    public ServerResponse productSave(Product product) {
        if (product != null) {
            //将子图的第一张图片设置为主图
            if (StringUtils.isNotBlank(product.getSubImages())) {
                String[] subImages = product.getSubImages().split(",");
                if (subImages.length > 0) product.setMainImage(subImages[0]);
            }
            if (product.getId() != null)
                return productMapper.updateByPrimaryKeySelective(product) > 0 ?
                        ServerResponse.createBySuccessMessage("更新成功!") :
                        ServerResponse.createByErrorMessage("更新失败!");
            return productMapper.insert(product) > 0 ?
                    ServerResponse.createBySuccessMessage("添加成功!") :
                    ServerResponse.createByErrorMessage("添加失败!");
        }
        return ServerResponse.createByErrorMessage("商品信息不正确!");
    }

    @Override
    public ServerResponse setSaleStatus(Integer productId, Integer status) {
        if (productId == null || status == null)
            return ServerResponse.createByErrorCode(ResponseInfo.ILLEGAL_ARGUMENT.getCode(), ResponseInfo.ILLEGAL_ARGUMENT.getDescription());
        Product product = new Product();
        product.setId(productId);
        product.setStatus(status);
        return productMapper.updateByPrimaryKeySelective(product) > 0 ?
                ServerResponse.createBySuccessMessage("修改产品销售状态成功!") :
                ServerResponse.createByErrorMessage("修改产品销售状态失败!");
    }

    /**
     * 后台获取指定id 的商品详细信息的VO 对象
     *
     * @param productId 商品id
     * @return 响应对象
     */
    @Override
    public ServerResponse<ProductDetailVo> manageProductDetail(Integer productId) {
        if (productId == null)
            return ServerResponse.createByErrorCode(ResponseInfo.ILLEGAL_ARGUMENT.getCode(), ResponseInfo.ILLEGAL_ARGUMENT.getDescription());
        Product product = productMapper.selectByPrimaryKey(productId);
        if (product == null)
            return ServerResponse.createByErrorMessage("商品已删除!");
        //pojo-->VO(value object)
        ProductDetailVo productDetailVo = assembleProductDetailVo(product);
        return ServerResponse.createBySuccess(productDetailVo);
        //pojo-->bo(business object)-->vo(view object)
    }

    private ProductDetailVo assembleProductDetailVo(Product product) {
        ProductDetailVo productDetailVo = new ProductDetailVo();
        productDetailVo.setId(product.getId());
        productDetailVo.setSubtitle(product.getSubtitle());
        productDetailVo.setPrice(product.getPrice());
        productDetailVo.setMainImage(product.getMainImage());
        productDetailVo.setSubImages(product.getSubImages());
        productDetailVo.setCategoryId(product.getCategoryId());
        productDetailVo.setDetail(product.getDetail());
        productDetailVo.setName(product.getName());
        productDetailVo.setStatus(product.getStatus());
        productDetailVo.setStock(product.getStock());

        //配置图片服务器前缀
        productDetailVo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix", "http://img.happymmall.com/"));

        //装配商品的父节点
        Category category = categoryMapper.selectByPrimaryKey(product.getCategoryId());
        if (category == null) productDetailVo.setParentCategoryId(0);
        else productDetailVo.setParentCategoryId(category.getParentId());

        productDetailVo.setCreateTime(DateTimeUtil.dateToStr(product.getCreateTime()));

        productDetailVo.setUpdateTime(DateTimeUtil.dateToStr(product.getUpdateTime()));

        return productDetailVo;
    }


    @Override
    @SuppressWarnings("unchecked")
    public ServerResponse<PageInfo> getList(Integer pageNum, Integer pageSize) {
        //startPage--start
        PageHelper.startPage(pageNum, pageSize);

        //填充自己的sql查询逻辑
        List<Product> products = productMapper.select();
        List<ProductListVo> productListVos = Lists.newArrayList();
        for (Product product : products)
            productListVos.add(assembleProductListVo(product));

        //pageHelper--收尾
        PageInfo pageResult = new PageInfo<>(products);
        pageResult.setList(productListVos);
        return ServerResponse.createBySuccess(pageResult);
    }

    private ProductListVo assembleProductListVo(Product product) {
        ProductListVo productListVo = new ProductListVo();
        productListVo.setId(product.getId());
        productListVo.setName(product.getName());
        productListVo.setCategoryId(product.getCategoryId());
        productListVo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix", "http://img.happymmall.com/"));
        productListVo.setMainImage(product.getMainImage());
        productListVo.setPrice(product.getPrice());
        productListVo.setSubtitle(product.getSubtitle());
        productListVo.setStatus(product.getStatus());
        return productListVo;
    }

    //返回查询结果的分页后的信息
    @Override
    public ServerResponse<PageInfo> search(String productName, Integer productId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        if (StringUtils.isNotBlank(productName)) {
//            productName = new StringBuilder().append("%").append(productName).append("%").toString();
            productName = "%" + productName + "%";
        }
        System.out.println("-----------------------------------------------------");
        List<Product> products = productMapper.selectByNameAndId(StringUtils.isBlank(productName) ? null : productName, productId);
        System.out.println("-----------------------------------------------------");
        List<ProductListVo> productListVos = Lists.newArrayList();
        for (Product product : products)
            productListVos.add(assembleProductListVo(product));
        PageInfo pageResult = new PageInfo<>(products);
        pageResult.setList(productListVos);
        return ServerResponse.createBySuccess(pageResult);
    }

    //前端与后端不同在于,前端会分析商品状态,判断商品下架则不返回.
    @Override
    public ServerResponse<ProductDetailVo> getDetail(Integer productId) {
        if (productId == null)
            return ServerResponse.createByErrorCode(ResponseInfo.ILLEGAL_ARGUMENT.getCode(), ResponseInfo.ILLEGAL_ARGUMENT.getDescription());
        Product product = productMapper.selectByPrimaryKey(productId);
        if (product == null)
            return ServerResponse.createByErrorMessage("商品已删除!");
        if (product.getStatus() != IConst.ProductStatus.ON_SALE.CODE) {
            return ServerResponse.createByErrorMessage("商品已下架!");
        }
        ProductDetailVo productDetailVo = assembleProductDetailVo(product);
        return ServerResponse.createBySuccess(productDetailVo);
    }

    //前台通过商品关键字和品类id来搜索子类商品信息
    @Override
    public ServerResponse<PageInfo> getProductByKeywordCategory(String keyword, Integer categoryId, Integer pageNum, Integer pageSize, String orderBy) {
        List<Integer> categoryIds = Lists.newArrayList();
        //如果关键字和id都为空则返回参数错误信息
        if (StringUtils.isBlank(keyword) && categoryId == null)
            return ServerResponse.createByErrorCode(ResponseInfo.ILLEGAL_ARGUMENT.getCode(), ResponseInfo.ILLEGAL_ARGUMENT.getDescription());

        if (categoryId != null) {
            Category category = categoryMapper.selectByPrimaryKey(categoryId);
            //没有关键字,且id返回品类为空,返回一个空的PageInfo
            if (category == null && StringUtils.isBlank(keyword)) {
                PageHelper.startPage(pageNum, pageSize);
                List<ProductListVo> productListVos = Lists.newArrayList();
                PageInfo pageInfo = new PageInfo<>(productListVos);
                return ServerResponse.createBySuccess(pageInfo);
            }
            //返回该Id最底层子分类的id集合
            if (category != null) {
                Set<Category> categorySet = iCategoryService.getChildrenLast(category.getId()).getData();
                for (Category temp : categorySet) {
                    categoryIds.add(temp.getId());
                }
            }
        }
        if (StringUtils.isNotBlank(keyword)) keyword = "%" + keyword + "%";
        PageHelper.startPage(pageNum, pageSize);
        //处理排序语句
        if (StringUtils.isNotBlank(orderBy)) {
            if (IConst.OrderBy.PRICE_ORDER.contains(orderBy)) {
                PageHelper.orderBy(orderBy);
            }
        }
        //这里不能直接传keyword和categoryIds.因为如果keyword为""或"  ",ids为一个size为0的非null集合.
        //依然会被传递到sql中并执行通过其中的if语句.使查询结果出现问题
        List<Product> products = productMapper.selectByNameAndCategoryIds(
                StringUtils.isBlank(keyword) ? "%" + keyword + "%" : keyword,
                CollectionUtils.isEmpty(categoryIds) ? null : categoryIds);
        List<ProductListVo> productListVos = Lists.newArrayList();
        products.forEach(a -> productListVos.add(assembleProductListVo(a)));
        PageInfo pageInfo = new PageInfo<>(products);
        pageInfo.setList(productListVos);
        return ServerResponse.createBySuccess(pageInfo);
    }

    @Test
    public void tt() {
        ServerResponse<PageInfo> sr = getProductByKeywordCategory("", 100012, 1, 10, "price desc");
        System.out.println(sr.getData().getList().size());
        for (Object o : sr.getData().getList()) {
            System.out.println(o.toString());
        }
    }
}
